//
//  CustomTabBar.m
//  DemoTest
//
//  Created by DaShuEdu on 2017/4/25.
//  Copyright © 2017年 DaShuEdu. All rights reserved.
//

#import "CustomTabBar.h"
#import "PlusButton.h"

@interface CustomTabBar ()

@property (nonatomic, copy) NSArray *tabBarButtonArray;
@property (nonatomic, assign) BOOL showAdd;
@property (nonatomic, strong) PlusButton *plusButton;

@end

@implementation CustomTabBar

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

/**
初始化-是否展示中间大按钮

@param showAdd 是否展示 BOOL
@return 返回实例对象
*/
- (instancetype)initWithShowAdd:(BOOL)showAdd {
    if (self = [super init]) {
        self.showAdd = showAdd;
    }
    return self;
}

- (instancetype)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.backgroundImage = [UIImage imageNamed:@"tabbar_bg"];
    }
    return self;
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    // 如果个数是奇数的话，则不按照 添加button处理
    if (self.items.count%2!=0) {
        self.showAdd = NO;
    }
    CGSize btnSize = CGSizeZero;
    if ([self.protocol respondsToSelector:@selector(plusButtonSize)]) {
        btnSize = [self.protocol plusButtonSize];
    }
    
    self.barStyle = UIBarStyleBlack;
    CGSize screenSize = [UIScreen mainScreen].bounds.size;
    CGFloat addBarWidth = btnSize.width;
    CGFloat itemWidth = screenSize.width/self.items.count;
    if (self.showAdd) {
        [self addSubview:self.plusButton];
        itemWidth = (screenSize.width-addBarWidth)/self.items.count;
    }
    
    NSArray *sortedSubviews = [self sortedSubviews];
    self.tabBarButtonArray = [self tabBarButtonFromTabBarSubviews:sortedSubviews];
    [self.tabBarButtonArray enumerateObjectsUsingBlock:^(UIView *_Nonnull view, NSUInteger idx, BOOL * _Nonnull stop) {
        CGFloat childViewX;
        if (self.showAdd && idx >= 2) {
            childViewX = idx * itemWidth + addBarWidth;
        } else {
            childViewX = idx * itemWidth;
        }
        
        view.frame = CGRectMake(childViewX, CGRectGetMinY(view.frame), itemWidth, CGRectGetHeight(view.frame));
    }];
    [self bringSubviewToFront:self.plusButton];
}

- (PlusButton *)plusButton {
    if (_plusButton == nil) {
        CGSize btnSize = CGSizeZero;
        if ([self.protocol respondsToSelector:@selector(plusButtonSize)]) {
            btnSize = [self.protocol plusButtonSize];
        }
        NSString *imageName = @"";
        if ([self.protocol respondsToSelector:@selector(plusButtonBackgroundImageName)]) {
            imageName = [self.protocol plusButtonBackgroundImageName];
        }
        CGSize screenSize = [UIScreen mainScreen].bounds.size;
        PlusButton *pB = [PlusButton buttonWithType:UIButtonTypeCustom];
        pB = [[PlusButton alloc] initWithFrame:CGRectMake((screenSize.width-btnSize.width)*0.5, 49-btnSize.height, btnSize.width, btnSize.height)];
        [pB setBackgroundImage:[UIImage imageNamed:imageName] forState:UIControlStateNormal];
        _plusButton = pB;
    }
    
    return _plusButton;
}

- (NSArray *)sortedSubviews {
    NSArray *sortedSubviews = [self.subviews sortedArrayUsingComparator:^NSComparisonResult(UIView * formerView, UIView * latterView) {
        CGFloat formerViewX = formerView.frame.origin.x;
        CGFloat latterViewX = latterView.frame.origin.x;
        return  (formerViewX > latterViewX) ? NSOrderedDescending : NSOrderedAscending;
    }];
    return sortedSubviews;
}

- (NSArray *)tabBarButtonFromTabBarSubviews:(NSArray *)tabBarSubviews {
    NSMutableArray *tabBarButtonMutableArray = [NSMutableArray arrayWithCapacity:tabBarSubviews.count - 1];
    [tabBarSubviews enumerateObjectsUsingBlock:^(UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj isKindOfClass:NSClassFromString(@"UITabBarButton")]) {
            [tabBarButtonMutableArray addObject:obj];
        }
    }];
    return [tabBarButtonMutableArray copy];
}

- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    
    if (self.showAdd) {
        CGRect plusButtonFrame = self.plusButton.frame;
        BOOL isInPlusButtonFrame = CGRectContainsPoint(plusButtonFrame, point);
        if (!isInPlusButtonFrame && (point.y < 0)) {
            return nil;
        }
        if (isInPlusButtonFrame) {
            return self.plusButton;
        }
    }
    
    if (!self.showAdd && self.items.count%2!=0) {
        CGSize screenSize = [UIScreen mainScreen].bounds.size;
        CGFloat itemW = screenSize.width / self.items.count;
        CGFloat minX = screenSize.width/2.0-itemW/2.0;
        CGFloat maxX = screenSize.width/2.0+itemW/2.0;
        if (point.x > maxX || point.x < minX) {
            if (![self pointInside:point withEvent:event]) {
                return nil;
            } else {
                return [self getPointInView:point];
            }
        }
        
        UIView *midTabBarButton = [self getTabBarButtonArr][self.items.count/2];
        for (UIView *subView in midTabBarButton.subviews) {
            CGRect subViewFrame = subView.frame;
            if (subViewFrame.origin.y<0 && subViewFrame.origin.y<=point.y-2) {
                NSLog(@"frame.origin.y:%f",subViewFrame.origin.y);
                NSLog(@"point.y:%f",point.y);
                point.y = point.y - subViewFrame.origin.y;
                break;
            }
        }
        if (![self pointInside:point withEvent:event]) {
            return nil;
        }
    }
    
    return [self getPointInView:point];
}

- (UIView *)getPointInView:(CGPoint)point {
    NSArray *tabBarButtons = [self getTabBarButtonArr];
    
    for (NSUInteger index = 0; index<tabBarButtons.count; index++) {
        UIView *selectedTabBarButton = tabBarButtons[index];
        CGRect selectedTabBarButtonFrame = selectedTabBarButton.frame;
        if (CGRectContainsPoint(selectedTabBarButtonFrame, point)) {
            return selectedTabBarButton;
        }
    }
    
    return nil;
}

- (NSArray *)getTabBarButtonArr {
    NSArray *tabBarButtons = self.tabBarButtonArray;
    if (self.tabBarButtonArray.count == 0) {
        tabBarButtons = [self tabBarButtonFromTabBarSubviews:self.subviews];
    }
    return tabBarButtons;
}

- (void)dealloc
{
    NSLog(@"%s",__func__);
}

@end
